package com.rephael.van.image;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 拍摄照片相关的工具类
 * Created by rephael on 15-6-5.
 */
public class TakePicture {
    private Context context;
    public TakePicture(Context context){
        this.context = context;
    }
    //判断用户设备是否具有照相功能
    public boolean isCameraAvilible(){
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    String mCurrentPhotoPath;//拍摄图片路径

    private File createImageFile() throws IOException {
        //	Create	an	image	file	name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String path_ = Environment.getExternalStorageDirectory().toString() + "/Temp/cache";
        File storageDir = /*Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)*/new File(path_);
        if(!storageDir.exists()){
            storageDir.mkdirs();
        }
        File image = File.createTempFile(
                imageFileName,		/*	prefix	*/
                ".jpg",									/*	suffix	*/
                storageDir						/*	directory	*/
        );
        //	Save	a	file:	path	for	use	with	ACTION_VIEW	intents
        mCurrentPhotoPath = /*"file:" + */image.getAbsolutePath();
        return image;
    }
    //调用系统相机拍摄照片
    public static final int REQUEST_TAKE_PHOTO = 1;

    public void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //	Ensure	that	there's	a	camera	activity	to	handle	the	intent
        if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
            //	Create	the	File	where	the	photo	should	go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                //	Error	occurred	while	creating	the	File
            }
            //	Continue	only	if	the	File	was	successfully	created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                ((Activity) context).startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    //处理照片结果
    public void takePictureResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == ((Activity)context).RESULT_OK){
            if(requestCode == REQUEST_TAKE_PHOTO){
                savePicToFile(resizePicture(540, 960));
            }
        }
    }
    //缩放图片并显示到控件上
    public void setPic(ImageView mImageView) {
        //	Get	the	dimensions	of	the	View
        int targetW = mImageView.getWidth();
        int targetH = mImageView.getHeight();
        //	Get	the	dimensions	of	the	bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;
        //	Determine	how	much	to	scale	down	the	image
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
        //	Decode	the	image	file	into	a	Bitmap	sized	to	fill	the	View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        mImageView.setImageBitmap(bitmap);
    }
    //根据给定的宽高缩放图片
    private Bitmap resizePicture(int width, int height){
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;
        int scaleFactor = Math.min(photoW / width, photoH / height);
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        return bitmap;
    }
    //将图片保存到SD卡中
    public void savePicToFile(Bitmap bitmap){
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String path_ = Environment.getExternalStorageDirectory().toString() + "/Temp/thumb";
        File storageDir = new File(path_);
        if(!storageDir.exists()){
            storageDir.mkdirs();
        }
        try {
            File file = File.createTempFile(
                    imageFileName,		/*	prefix	*/
                    ".jpg",									/*	suffix	*/
                    storageDir						/*	directory	*/
            );
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
